<?php echo $this->element('displayHeader'); ?>
<?php echo $ajax->form('ItsStocksIn', 'post', array('update'=>'content', 'indicator' => 'indicator', 'url' => array('action' => 'save')));?>
<div class="toolbar">
    <div id="tLeft">
        <?php if ($mode == 'add') : ?>
            <?php echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back'))); ?>
        <?php else :  // mode edit ?>
            <?php echo $this->element('toolbar', array('buttons' => array('add',array('print' => array('model' => 'ItsStockInHead')), 'back'))); ?>
        <?php endif; ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'ItsStockInHead', 'title' => 'id')); ?></div>
</div>

<?php echo $form->input('ItsStockInHead.id'); ?>
<fieldset>
    <table>
        <tr>
            <td width="180px"><?php echo $form->label('ItsStockInHead.stock_in_no', 'Stock in no.'); ?></td>
            <td width="300px">
                <?php if ($mode == 'add') : ?>
                <?php else : ?>
                    <?php echo $this->data['ItsStockInHead']['stock_in_no'] ?>
                <?php endif; ?>
            </td>
            <td width="180px"><?php echo $form->label('ItsStockInHead.supplier_id', 'Vendor', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('ItsStockInHead.supplier_id', array('id' => 'hidItsStockInHeadSupplierId')); ?>
                    <?php echo $form->select('ItsStockInHead.supplier_id', $suppliers, null, !empty($this->data['ItsStockInHead']['supplier_id'])? array('disabled' => 'disabled', 'tabindex' => 5): array('tabindex' => 5)); ?>
                <?php else : ?>
                <span id="supplier_id"><?php echo $this->data['Supplier']['name'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('ItsStockInHead.stock_in_date', 'Stock in date', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $html->tag('span', $today); ?>
                    <?php echo $form->hidden('ItsStockInHead.stock_in_date', array('id' => 'stock_in_date', 'value' => $today)); ?>
                <?php else : ?>
                <span id="stock_in_date"><?php echo $this->data['ItsStockInHead']['stock_in_date'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('ItsStockInHead.warehouse_id', 'Warehouse', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->hidden('ItsStockInHead.warehouse_id', array('id' => 'hidItsStockInHeadWarehouseId')); ?>
                    <?php echo $form->select('ItsStockInHead.warehouse_id', $warehouses, null, !empty($this->data['ItsStockInHead']['warehouse_id'])? array('disabled' => 'disabled', 'tabindex' => 5): array('tabindex' => 5)); ?>
                <?php else : ?>
                <span id="supplier_id"><?php echo $this->data['Warehouse']['name'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('ItsStockInHead.po_no', 'Ref. by PO no', array('class' => 'required')); ?></td>
            <td>
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->text('ItsStockInHead.po_no', array('tabindex' => 2)); ?>
                <?php else : ?>
                <span id="po_no"><?php echo $this->data['ItsStockInHead']['po_no'] ?></span>
                <?php endif; ?>
            </td>
            <td><?php echo $form->label('ItsStockInHead.stock_in_by', 'Stock in by'); ?></td>
            <td>
                <?php if($mode == 'add') : ?>
                    <?php echo $html->tag('span', $stock_in_by); ?>
                    <?php echo $form->hidden('ItsStockInHead.stock_in_by', array('value' => $stock_in_by)); ?>
                <?php else : ?>
                    <?php echo $html->tag('span', $this->data['ItsStockInHead']['stock_in_by']); ?>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <td><?php echo $form->label('ItsStockInHead.cust_pr_no', 'Ref. by Customer PR no', array('class' => 'required')); ?></td>
            <td colspan="3">
                <?php if ($mode == 'add') : ?>
                    <?php echo $form->text('ItsStockInHead.cust_pr_no', array('tabindex' => 3)); ?>
                <?php else : ?>
                <span id="cust_pr_no"><?php echo $this->data['ItsStockInHead']['cust_pr_no'] ?></span>
                <?php endif; ?>
            </td>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th class="no">No</th>
                <th width="180px">Part no.</th>
                <th>Description</th>
                <th width="100px">Stock in Qty</th>
                <?php if($mode == 'add') : ?>
                <th width="120px">Location</th>
                <?php endif; ?>
                <th width="50px">Unit</th>
                <th width="80px">Cost/Unit</th>
                <th width="80px">Amount</th>
                <?php if($mode == 'edit') : ?>
                <th width="50px">Index</th>
                <?php endif; ?>
                <?php if($mode == 'add') : ?>
                <th class="action">&nbsp;</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php if ($mode == 'add') : ?>
            <?php else : $count = count($this->data['ItsStockIn'])// mode edit ?>
                <?php for($i = 0; $i < $count; ++$i) : ?>
            <tr class="<?php echo (($i + 1) % 2 == 0)? 'even-cell' : 'odd-cell'; ?>">
                <td><span><?php echo $i + 1; ?></span></td>
                <td>
                            <?php echo $html->link($this->data['ItsStockIn'][$i]['Product']['part_no'],
                            '/products/view/' . $this->data['ItsStockIn'][$i]['product_id'] . '/' . strtotime('now'),
                            array('target' => '_blank')); ?>
                </td>
                <td><?php echo $this->data['ItsStockIn'][$i]['Product']['title']; ?></td>
                <td class="text-right"><?php echo $this->data['ItsStockIn'][$i]['stock_in_qty']; ?></td>
                <td class="center"><?php echo $this->data['ItsStockIn'][$i]['Product']['Unit']['title']; ?></td>
                <td class="text-right"><?php echo number_format($this->data['ItsStockIn'][$i]['cost'], 2); ?></td>
                <td class="text-right"><?php echo number_format($this->data['ItsStockIn'][$i]['cost'] * $this->data['ItsStockIn'][$i]['stock_in_qty'], 2); ?></td>
                <td class="center">
                            <?php echo $ajax->link($html->image('icon/popup.png', array('alt' => 'Index information')),
                            array('controller' => 'products_serials', 'action' => 'popup_view', $this->data['ItsStockIn'][$i]['product_id'] . '/' . 'its_stock_in_id:' . $this->data['ItsStockIn'][$i]['id'] . '/its_stock_in_type:' . ItsStockIn::STOCK_IN_TYPE),
                            array('update' => 'content', 'position' => 'bottom', 'indicator' => 'indicator' ), null, false); ?>
                </td>
            </tr>
                <?php endfor; ?>
            <?php endif; ?>
        </tbody>
    </table>
</fieldset>

<?php echo $form->end(); ?>

<?php if ($mode == 'add') : ?>
    <?php echo $form->select('ItsStockIn.location_id', null, null, array('style' => 'display: none;')); ?>
<script type="text/javascript">
    // JSON เ�?�?�? part no ที�?�?�?อ�?เ�?�?ามา อ�?า�?�?�?ยั�?ลำดั�?�?ถว
    var partNos = {};

    requestProduct = function(event) {
        var element = Event.element(event);
        var part_no = $j.trim($F(element)).toUpperCase();
        var no = element.readAttribute("no");   // ลำดั�?�?ถว�?ั�?�?ุ�?ั�? เริ�?มที�? 0

        if(part_no.length == 0) {
            return;
        } else if ($F("ItsStockInHeadSupplierId") == "") {
            alert("Please select a Vendor first");
            $(event.target).clear();
            return;
        } else if ($F("ItsStockInHeadWarehouseId") == "") {
            alert("Please select a warehouse first");
            $(event.target).clear();
            return;
        } else {
            $("ItsStockInHeadSupplierId").disable();
            $("hidItsStockInHeadSupplierId").value = $F("ItsStockInHeadSupplierId");
            $("ItsStockInHeadWarehouseId").disable();
            $("hidItsStockInHeadWarehouseId").value = $F("ItsStockInHeadWarehouseId");
        }

        // ถ�?ายั�?�?ม�?มี part no �?ี�?อยู�?
        if (partNos[part_no] == null) {
            var url = base + "/products/json_find_by_part_no_supplier/";
            var params = {part_no: part_no, supplier_id: $F("ItsStockInHeadSupplierId")};
            postRequest(url, params, function(data) {
                //$("test").update(data);
                if (data.Product) { // �?�? Product
                } else { // �?ม�?�?�?�?�?อมูล (�?รอ�?�?�?อมูล�?ิด...)
                    alert("No product found or incorrect product Vendor.");
                    element.clear();
                    $("ItsStockIn" + no + "PartNo").focus();
                    return;
                }
                setItsStockIn(data, part_no, no);
//                createSerialElement(no);
            });
        } else {
            element.clear();
            var row = partNos[part_no]; // �?ถวที�?มี part_no �?ี�?อยู�?
            $("ItsStockIn" + row + "StockInQty").value = parseInt($("ItsStockIn" + row + "StockInQty").value) + 1;
            calAmount(row);
            setTimeout(function() {
                $("ItsStockIn" + no + "PartNo").focus();
            }, 100);
//            createSerialElement(row);
        }
    }

    setItsStockIn = function(data, part_no, no) {
        $("ItsStockIn" + no + "Title").update(data.Product.text);
        $("ItsStockIn" + no + "PartNo").hide();
        $j("#linkItsStockIn" + no + "ProductId").hide();
        $("ItsStockIn" + no + "PartNoSpan").update(data.Product.part_no);
        $("ItsStockIn" + no + "PartNoSpan").show();
        $("ItsStockIn" + no + "ProductId").value = data.Product.id;
        $("ItsStockIn" + no + "ProductUnit").update(data.Unit.title);
        $("ItsStockIn" + no + "Cost").value = data.Product.cost;
        $("ItsStockIn" + no + "UnitId").value = data.Product.unit_id;
        $("ItsStockIn" + no + "StockInQty").value = 1;

        $j("#ItsStockInLocationId").clone().appendTo("#LocationTd" + no).attr({
            id: "ItsStockIn" + no + "LocationId",
            name: "data[ItsStockIn][" + no + "][location_id]",
            no: no
        }).show();
        // ดักจับ Event กดลบแถว
        $j('#linkItsStockIn' + no + 'Delete').bind('click', function() {
            // ลบรายการ part no ออกจาก list
            var p = $j("#ItsStockIn" + no + "PartNoSpan").text();
            partNos[p] = undefined;

            // ลบ แถว
            $j('#ItsStockIn' + no + 'Id').parents('tr').remove();

            // จัดลำดับตัวเลขหน้าแถวใหม่
            $j('#productRow').runno();
        }).show();

        calAmount(no);
        partNos[part_no] = no;  // �?ั�?ทึ�?�?ถว�?ั�?�?ุ�?ั�?�?อ�? part no
        var nextRow = (parseInt(no) + 1);
        createRow(nextRow)
        $("ItsStockIn" + nextRow + "PartNo").focus();
    }

    calAmount = function(no) {
        var stockInQty = parseInt($F("ItsStockIn" + no + "StockInQty"))
        var cost = parseFloat($F("ItsStockIn" + no + "Cost"))
        var amount = stockInQty * cost;
        if (!isNaN(amount)) {
            $("ItsStockIn" + no + "TotalCost").update(amount.toFixed(2));
        }
    }

    productsHandler = function(part_no) {
        if (part_no != null) {
            // หา input part no ที่ยังแสดงอยู่ (มีอันเดียวเสมอ)
            $j("input[id$=PartNo]:visible").val(part_no).focus().blur();
        }
    }

    createRow = function(row) {
        var tBody = $("productRow");
        var tr = new Element("tr");
        tr.addClassName(((row + 1) % 2 == 0)? "even-cell" : "odd-cell");

        tr.update('<input id="ItsStockIn' + row + 'Id" type="hidden" value="" name="data[ItsStockIn][' + row + '][id]" />');

        var tdNo = new Element("td");
        tdNo.update('&nbsp;');
        tr.insert(tdNo);

        var tdPartNo = new Element("td");
        tdPartNo.insert('<input id="ItsStockIn' + row + 'PartNo" type="text" value="" no="' + row + '" name="data[ItsStockIn][' + row + '][part_no]"/>');
        tdPartNo.insert('<input id="ItsStockIn' + row + 'ProductId" type="hidden" value="" name="data[ItsStockIn][' + row + '][product_id]"/>');
        tdPartNo.insert('<span id="ItsStockIn' + row + 'PartNoSpan" style="display: none"></span>');
        tdPartNo.insert('&nbsp;<a href="#" id="linkItsStockIn' + row + 'ProductId"><?php echo $html->image('icon/search.png'); ?></a>');
        tr.insert(tdPartNo);

        var tdTitle = new Element("td");
        tdTitle.insert('<span id="ItsStockIn' + row + 'Title"></span>');
        tr.insert(tdTitle);

        var tdStockInQty = new Element("td");
        var div = new Element("div", {'class': 'inline'});
        div.update('<input id="ItsStockIn' + row + 'StockInQty" no="' + row + '" class="text-right" type="text" value="" maxlength="5" size="5" name="data[ItsStockIn][' + row + '][stock_in_qty]"/>');
        tdStockInQty.insert(div);
        tr.insert(tdStockInQty);

        var tdLocation = new Element("td", {id: "LocationTd" + row});
        tr.insert(tdLocation);

        var tdUnit = new Element("td", {'class': 'center'});
        tdUnit.insert('<span id="ItsStockIn' + row + 'ProductUnit"></span>');
        tdUnit.insert('<input id="ItsStockIn' + row + 'UnitId" type="hidden" value="" name="data[ItsStockIn][' + row + '][unit_id]"/>');
        tr.insert(tdUnit);

        var tdCost = new Element("td");
        tdCost.insert('<input id="ItsStockIn' + row + 'Cost" no="' + row + '" class="text-right" type="text" value="" maxlength="10" size="10" name="data[ItsStockIn][' + row + '][cost]" />');
        tr.insert(tdCost);

        var tdAmount = new Element("td", {'class': 'text-right'});
        tdAmount.insert('<span id="ItsStockIn' + row + 'TotalCost"></span>');
        tr.insert(tdAmount);

        var tdDelete = new Element("td", {"class": "center"});
        tdDelete.insert('<a href="#" id="linkItsStockIn' + row + 'Delete" style="display: none;"><?php echo $html->image('icon/delete.png', array('title' => 'Delete', 'alt' => 'Delete')); ?></a>');
        tr.insert(tdDelete);

        tBody.insert(tr);

        // กำหนดลำดับเลขแต่ละแถวใหม่
        $j('#productRow').runno();
        addRowListener(row);
    }

    addRowListener = function(row) {
        $j("#ItsStockIn" + row + "PartNo").bind('keypress', partNoKeyPress);
        $j("#ItsStockIn" + row + "PartNo").bind('blur', function(event) {
            requestProduct(event);
        });

//        $j("#linkItsStockIn" + row + "ProductId").popup();
        $("linkItsStockIn" + row + "ProductId").observe('click', function(event) {
            var url = base + "/products/popup_view";
            // ถ้าเลือก Vendor แล้วส่งไปเป็นเงื่อนไขด้วยเลย
            if ($j('#ItsStockInHeadSupplierId').val() != "") {
                url += "/supplier_id:" + $j('#ItsStockInHeadSupplierId').val();
            }
            requestPopup(url, "productsHandler");
        });

        $("ItsStockIn" + row + "StockInQty").observe('keypress', stopKeyEnter);
        $("ItsStockIn" + row + "StockInQty").observe('change', function(event) {
            calAmount(Event.element(event).readAttribute("no"));
//            createSerialElement(row);
        });

        $("ItsStockIn" + row + "Cost").observe('keypress', stopKeyEnter);
        $("ItsStockIn" + row + "Cost").observe('change', function(event) {
            calAmount(Event.element(event).readAttribute("no"));
        });

        initPopUpIndex(row);
    }

    /**
     * onload
     */
    $j(function() {
        /**
         * validate ข้อมูลด้วย javascript ก่อน Save
         */
        $j('#ItsStockInHeadId').parent('form').beforeSubmit(function() {
            if ($j.areEmpty('ItsStockInHeadPoNo', 'ItsStockInHeadCustPrNo', 'ItsStockInHeadSupplierId', 'ItsStockInHeadWarehouseId')) {
                return false;
            }
            if ($j('#ItsStockIn0PartNo').length == 0) {
                if (!$j.validateField('ItsStockIn0PartNo', 'Product', 'ItsStockIn0PartNo')) {
                    return false;
                }
            }

            if (!$j.validateColumns('StockInQty', 'Stock in Qty', {callback: $j.QTY})) {
                return false;
            }
            if (!$j.validateColumns('Cost', 'Cost/Unit', {callback: $j.AMOUNT})) {
                return false;
            }

            return true;
        });

        $j("#ItsStockInHeadWarehouseId").bind('change', function() {
            requestOptions("warehouses", "ItsStockInHeadWarehouseId", "ItsStockInLocationId", false, 'option_location_list');   // false for not empty option
        });
        createRow(0);
    })
</script>
<?php endif; ?>
<?php //debug($this->data); ?>